﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using Data.MyDbContext;
using WebIndex.Models;
using System.Threading.Tasks;
using DAL;
using Data.DBModels;
//using WebIndex.Models;

namespace WebIndex.Controllers
{
    //[Authorize]
    public class AccountController : Controller
    {
        private readonly UnitOfRepositories _repositories=null;
        public AccountController(UnitOfRepositories repositories)
        {
            _repositories = repositories;
        }
        //
        // GET: /User/
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel user)
        {
            if (ModelState.IsValid)
            {
                if (_repositories.UserRepo.VerifyUser(user.UserName, user.Password))
                {
                    FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Login data is incorrect!");
                }
            }
            return View(user);
        }
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_repositories.UserRepo.Exists(item => item.Username == model.UserName))
                {
                    var user = new User() { Username = model.UserName, Password = model.Password, CreatedOn = DateTime.Now, Id = Guid.NewGuid() };

                    _repositories.UserRepo.Add(user);
                }
                else
                {

                    AddErrors("The UserName existed already!");
                }
                
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        private void AddErrors(string error)
        {
            
                ModelState.AddModelError("", error);
            
        }

       
    }
}
